import { useFetcher } from "react-router";
import type { Route } from "./+types/disable-form";

import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { Button } from "~/components/ui/button";
import { useCallback } from "react";
import { ThemeTrigger } from "~/components/theme-trigger";


export function meta({ }: Route.MetaArgs) {
  return [
    { title: "表单禁用" },
    { name: "description", content: "一个禁用的表单!" },
  ];
}

export const action = async (args: Route.ClientActionArgs) => {
  console.log(await args.request.formData());
  return new Promise((res, rej) => {
    setTimeout(res, 3000)
  })

}


const formSchema = z.object({
  username: z.string().min(2, {
    message: "用户名至少2个字符",
  }),
})


export default function DisableExample() {
  const fetcher = useFetcher();
  const form = useForm<z.infer<typeof formSchema>>({
    disabled: fetcher.state !== 'idle',
    resolver: zodResolver(formSchema),
    defaultValues: {
      username: "",
    },
  })


  // 2. Define a submit handler.
  const onSubmit = useCallback((values: z.infer<typeof formSchema>) => {
    // Do something with the form values.
    // ✅ This will be type-safe and validated.
    fetcher.submit(values, {
      method: "post",
    })
  }, [])
  return (<div className="p-4">
    <Form {...form} >
      <fetcher.Form method="post" onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
        <FormField
          control={form.control}
          name="username"
          render={({ field }) => (
            <FormItem>
              <FormLabel>用户名</FormLabel>
              <FormControl>
                <Input placeholder="shadcn" {...field} />
              </FormControl>
              <FormDescription>
                这是你的公开的显示名称。
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button className=" rounded" disabled={form.formState.disabled} type="submit">提交</Button>
      </fetcher.Form>
    </Form>
  </div>
  )
}